package work;

/**
 * @TODO
 * @Author xu
 * 2025/2/24
 */
public class Day4_3 {
    public static void main(String[] args) {
        int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
        int target = 11;

        int index = binarySearch(sortedArray, target);

        if (index != -1) {
            System.out.println("元素 " + target + " 在数组中的索引为: " + index);
        } else {
            System.out.println("数组中未找到元素 " + target);
        }
    }

    public static int binarySearch(int[] array, int target) {
        int low = 0;
        int high = array.length - 1;

        while (low <= high) {
            int mid = low + (high - low) / 2;

            if (array[mid] == target) {
                return mid;
            } else if (array[mid] < target) {
                low = mid + 1;
            } else {
                high = mid - 1;
            }
        }

        return -1;
    }

}
